﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.ServiceModel;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using AcceptServer.Service;
using Common;
using Model;
using PositionServer.Service;


namespace AcceptServer
{
    public partial class AcceptMainForm : Form
    {
        public AcceptMainForm()
        {
            InitializeComponent();
            label_version.Text = StrVersion;
        }


        // public static string RentCar_phoneNumbers = string.Empty;


        public static IPositionService PositionService;
        public static string ServerWebIp;
        //  private static string _serverLanIp;


        //public static readonly Hashtable  RentCarList = Hashtable.Synchronized(new Hashtable());

        private const string StrVersion = "1.0.2_bata3";
        public readonly static Hashtable IpEndPointList = Hashtable.Synchronized(new Hashtable());
        private readonly Hashtable _ipEndPointTimeList = Hashtable.Synchronized(new Hashtable());

        private Socket _transferSocket;
        readonly TQueue<byte[]> _dateQueue = new TQueue<byte[]>();
        public static readonly TQueue<TaxiGpsHistoryInfo> DataQueue = new TQueue<TaxiGpsHistoryInfo>();
        readonly OperateDataBase _operateDataBase = new OperateDataBase();

        private UdpServer _server;
        private UdpServer _server2;

        static Socket _udpClientChinaNet;
        static Socket _udpClientUniCom;
        private IPEndPoint _ipepChinaNet;
        private IPEndPoint _ipepUniCom;


        private int _dataHandlerThreadCount = 1;
        private int _dataBaseHandlerThreadCount = 1;


        private Thread[] _threadDataHandler;//数据处理线程
        private Thread[] _threadTaxiGpsHistoryInfoHandler;//数据处理线程

        private Thread _ipEndPointClearThread;
        private Thread _tTransferSocketRece;
        private Thread _tCdmaTaxiClearThread;

        // readonly IPEndPoint _ipep = new IPEndPoint(IPAddress.Any, ConstParameters.AstPort);
        private const string LocalhostIP = "127.0.0.1";

        // public static List<string> StationList=new List<string>();

        public static Hashtable StationList = Hashtable.Synchronized(new Hashtable());
        public static Hashtable PrivateCarRegistCodeList = Hashtable.Synchronized(new Hashtable());
        public static Hashtable CdmaTaxiList = Hashtable.Synchronized(new Hashtable());

        public static string PrivateCarClientVersion = "100";
        public static string TaxiClientVersion = "100";
        public static string PhoneUserClientVersion = "100";
        public static string SpecialCarClientVersion = "100";
        public static int PhonePlatformVersion = 100;

         

        //!--1
        private void StartServecie()
        {

            // RentCar_phoneNumbers = LogService.GetRentCarList();//12345678901,12345678901
            //----save config
            string[] config = new string[5];
            config[0] = textBox_PosIP.Text;
            config[1] = textBox_ChinaNetIp.Text;
            config[2] = textBox_UnicomIp.Text;
            config[3] = textBox_PhoneNumber.Text;
            config[4] = textBox_TransferServerip.Text;
            OperateConfig.SaveAcceptServerConfig(config);


            //读取客户端最新版本号
            PrivateCarClientVersion = OperateConfig.GetPrivateCarClientVersion();
            TaxiClientVersion = OperateConfig.GetTaxiClientVersion();
            PhoneUserClientVersion = OperateConfig.GetPhoneUserClientVersion();
            SpecialCarClientVersion = OperateConfig.GetSpecialCarClientVersion();            
            int.TryParse(OperateConfig.GetPhonePlatformVersion(), out PhonePlatformVersion);

            if (InitWcfService(textBox_PosIP.Text))
            {
                InitControlAfterStartService();

                try
                {

                    _transferSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    IPEndPoint address = new IPEndPoint(IPAddress.Parse(textBox_TransferServerip.Text), ConstParameters.TransferListenPort);
                    _transferSocket.NoDelay = true;
                    _transferSocket.Connect(address);



                    ServerWebIp = textBox_ChinaNetIp.Text;
                    _tTransferSocketRece = new Thread(TransferSocketRece) { IsBackground = true, Name = "_tTransferSocketRece----------------------------------------------" };
                    _tTransferSocketRece.Start();

                    if (textBox_ChinaNetIp.Text != LocalhostIP)
                    {
                        _server = new UdpServer(textBox_ChinaNetIp.Text, ConstParameters.AstPort);
                        _server.OnReceivedData += server_OnDataReceived;
                        _server.Start();
                    }

                    if (textBox_UnicomIp.Text != LocalhostIP)
                    {
                        _server2 = new UdpServer(textBox_UnicomIp.Text, ConstParameters.AstPort);
                        _server2.OnReceivedData += server_OnDataReceived;
                        _server2.Start();
                    }

                    if (textBox_ChinaNetIp.Text != LocalhostIP)
                    {
                        _ipepChinaNet = new IPEndPoint(IPAddress.Parse(textBox_ChinaNetIp.Text), ConstParameters.AstPort);
                        _udpClientChinaNet = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                        _udpClientChinaNet.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                        _udpClientChinaNet.Bind(_ipepChinaNet);
                    }
                    if (textBox_UnicomIp.Text != LocalhostIP)
                    {
                        _ipepUniCom = new IPEndPoint(IPAddress.Parse(textBox_UnicomIp.Text), ConstParameters.AstPort);
                        _udpClientUniCom = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                        _udpClientUniCom.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                        _udpClientUniCom.Bind(_ipepUniCom);
                    }



                    _threadTaxiGpsHistoryInfoHandler = new Thread[_dataBaseHandlerThreadCount];
                    for (int i = 0; i < _dataBaseHandlerThreadCount; i++)
                    {
                        this._threadTaxiGpsHistoryInfoHandler[i] = new Thread(AddTaxiGpsHistoryInfo);
                        this._threadTaxiGpsHistoryInfoHandler[i].Start();
                    }

                    this._threadDataHandler = new Thread[_dataHandlerThreadCount];
                    for (int i = 0; i < _dataHandlerThreadCount; i++)
                    {
                        this._threadDataHandler[i] = new Thread(UdpSendData);
                        this._threadDataHandler[i].Start();
                    }


                    _ipEndPointClearThread = new Thread(IpEndPointClear) { IsBackground = true, Name = "IPEndPointClearThread----------------------------------------------" }; ;
                    _ipEndPointClearThread.Start();

                    _tCdmaTaxiClearThread = new Thread(CdmaTaxiUpdate){IsBackground = true};
                    _tCdmaTaxiClearThread.Start();
                }
                catch (Exception ex)
                {
                    InitControlAfterStopService();
                    CommonRoutine.HandlingExceptions(ex, true);
                    LogService.WriteLog("AcceptMainForm.cs-155");
                }

            }
            else
            {
                MessageBox.Show(@"位置服务器连接失败！");
            }



        }

        private void AddTaxiGpsHistoryInfo()
        {
            while (true)
            {
                Thread.Sleep(60 * 60 * 1000);
                if (DataQueue.Count < 1)
                {
                    Thread.Sleep(60000);
                    continue;
                }

                try
                {

                    while (DataQueue.Count > 0)
                    {
                        StringBuilder sb = new StringBuilder();
                        sb.Append("set names  'utf8';insert into ttaxigpshistory");
                        sb.Append("(DriverPhoneNumber,Longitude,Latitude,Updatetime,Taxistate,image) ");
                        sb.Append("values ");
                        int tempCount = 0;
                        while (tempCount < 5000)
                        {
                            if (DataQueue.Count > 0)
                            {
                                tempCount++;
                                TaxiGpsHistoryInfo model = DataQueue.Dequeue();
                                if (model.Taxistate == 21 || model.Taxistate == 22 ||
                                    model.Taxistate == 23 || model.Taxistate == 24)
                                {
                                    model.Taxistate = 2;
                                }
                                if (model.Taxistate==20)
                                {
                                    model.Taxistate = 0;
                                }
                                sb.Append("('");
                                sb.Append(model.DriverPhoneNumber);
                                sb.Append("','");
                                sb.Append(model.Longitude);
                                sb.Append("','");
                                sb.Append(model.Latitude);
                                sb.Append("','");
                                sb.Append(model.Time);
                                sb.Append("','");
                                sb.Append(model.Taxistate);
                                sb.Append("',");
                                sb.Append("null)");
                                //if (DataQueue.Count > 0)
                                //{
                                //    sb.Append(",");
                                //}   
                                sb.Append(",");
                            }
                            else
                            {
                                break;
                            }

                        }
                        sb.Remove(sb.Length - 1, 1);
                        int rows = _operateDataBase.AddListTaxiGpsHistory(sb.ToString());
                    }


                    //StringBuilder sb = new StringBuilder();
                    //sb.Append("set names  'utf8';insert into ttaxigpshistory");
                    //sb.Append("(DriverPhoneNumber,Longitude,Latitude,Updatetime,Taxistate,image) ");
                    //sb.Append("values ");
                    //while (DataQueue.Count > 0 && tempCount < 10000)
                    //{
                    //    tempCount++;
                    //    TaxiGpsHistoryInfo model = DataQueue.Dequeue();
                    //    sb.Append("('");
                    //    sb.Append(model.DriverPhoneNumber);
                    //    sb.Append("','");
                    //    sb.Append(model.Longitude);
                    //    sb.Append("','");
                    //    sb.Append(model.Latitude);
                    //    sb.Append("','");
                    //    sb.Append(model.Time);
                    //    sb.Append("','");
                    //    sb.Append(model.Taxistate);
                    //    sb.Append("',");
                    //    sb.Append("null)");
                    //    if (DataQueue.Count > 0)
                    //    {
                    //        sb.Append(",");
                    //    }

                    //}
                    //int rows = _operateDataBase.AddListTaxiGpsHistory(sb.ToString());

                    // TaxiGpsHistoryInfo taxiGpsHistoryInfo = DataQueue.Dequeue();
                    //_operateDataBase.AddTaxiGpsHistoryInfo(taxiGpsHistoryInfo);
                }
                catch (Exception ex)
                {
                    LogService.WriteLog(ex.Message);
                    LogService.WriteLog("AcceptMainForm.cs-185");
                }

            }
        }

        public static void SendDataToIPAddress(byte[] data, IPEndPoint ipEndPoint, string sendToPhoneNumber)
        {
            //Socket sendSocket = JudgeIsUnicomNumber(sendToPhoneNumber);
            //sendSocket.SendTo(data, data.Length, SocketFlags.None, ipEndPoint);

            if (_udpClientChinaNet != null)
                _udpClientChinaNet.SendTo(data, data.Length, SocketFlags.None, ipEndPoint);
            if (_udpClientUniCom != null)
                _udpClientUniCom.SendTo(data, data.Length, SocketFlags.None, ipEndPoint);
        }



        void server_OnDataReceived(object sender, EventArgs e)
        {
            SocketAsyncEventArgs socketAsyncEventArgs = e as SocketAsyncEventArgs;
            if (socketAsyncEventArgs != null)
            {
                if (socketAsyncEventArgs.BytesTransferred >= ConstParameters.MhLenth)
                {
                    byte[] receData = new byte[socketAsyncEventArgs.BytesTransferred];
                    
                    Array.Copy(socketAsyncEventArgs.Buffer, 0, receData, 0, receData.Length);
                    byte[] realData = OperateAgreement.RestoreReceData(receData); 
                    if (OperateAgreement.JudgeisCompleteData(realData))
                    {
                        string phoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);

                        if (phoneNumber.Length == 12)
                        {
                            if (!StationList.ContainsKey(phoneNumber))
                            {
                                //暂时只用到了 更新时间及版本号
                                AdStationInfo station = new AdStationInfo();
                                station.Machine.Number = phoneNumber;
                                station.IsOnline = true;
                                station.UpdateTime = DateTime.Now;
                                StationList[phoneNumber] = station;
                            }
                            else
                            {
                                AdStationInfo adStation = StationList[phoneNumber] as AdStationInfo;
                                adStation.UpdateTime = DateTime.Now;
                            }
                        }


                        if (!IpEndPointList.Contains(phoneNumber))
                        {
                            #region
                            //    TcpCount  Add 
                            try
                            {
                                PositionService.AsTcpCountAdd(ServerWebIp, phoneNumber);
                                _transferSocket.Send(receData);
                            }
                            catch (Exception ex)
                            {
                                RestTransferSocket();
                                CommonRoutine.HandlingExceptions(ex);
                                LogService.WriteLog("AcceptMainForm.cs-225");
                                return;
                            }
                            #endregion

                            #region LogPrint
                            LogService.WriteDebugLog(phoneNumber + "---连接成功！IP :  " + socketAsyncEventArgs.RemoteEndPoint, DateTime.Now, phoneNumber);
                            #endregion
                        }
                        _ipEndPointTimeList[phoneNumber] = DateTime.Now;
                        IpEndPointList[phoneNumber] = socketAsyncEventArgs.RemoteEndPoint;

                        _dateQueue.Enqueue(receData);
                        #region LogPrint
                        ushort messageId = OperateAgreement.GetMessageIdInMessageHead(realData);
                        LogService.WriteDebugLog("号码：" + phoneNumber + "，消息Id：0x" +
                            messageId.ToString("X2").PadLeft(4, '0') + ",IP:" + socketAsyncEventArgs.RemoteEndPoint, DateTime.Now, phoneNumber);

                        #endregion
                         
                    }
                    else if (OperateAgreement.JudgeisCompleteDataOfCdma(receData))//CDMA msg
                    {
                        string deviceNumber = OperateAgreement.GetCdmaDeviceNumber(receData);
                        //if (!IpEndPointList.Contains(deviceNumber))
                        //{
                            
                        //} 
                        _ipEndPointTimeList[deviceNumber] = DateTime.Now;
                        IpEndPointList[deviceNumber] = socketAsyncEventArgs.RemoteEndPoint;

                        _dateQueue.Enqueue(receData);
                    }
                                  
                }
                 


            }


        }

        private void UdpSendData()
        {
            TaxiProtocol taxiProtocol = new TaxiProtocol();
            while (true)
            {
                if (_dateQueue.Count < 1)
                {
                    Thread.Sleep(1000);
                    continue;
                }

                byte[] receData;
                lock (_dateQueue)
                {
                    receData = _dateQueue.Dequeue(); 
                }
                //this.BeginInvoke(new MethodInvoker(delegate()
                //{
                //    label_SokcetCount.Text = _ipEndPointList.Count.ToString();
                //    label_DataHandlerThreadCount.Text = _dateQueue.Count.ToString();
                //    label_DataBaseHandlerThreadCount.Text = DataQueue.Count.ToString();
                //}));
                
                if (OperateAgreement.JudgeisCompleteDataOfCdma(receData))
                {
                    try
                    {
                        string deviceNumber = OperateAgreement.GetCdmaDeviceNumber(receData);
                        IPEndPoint ipEndPoint = IpEndPointList[deviceNumber] as IPEndPoint;
                        if (ipEndPoint == null) continue;
                        taxiProtocol.CdmaTaxiUpdataGpsInfo(receData, ipEndPoint.Address); 
                    }
                    catch (Exception ex)
                    {
                        LogService.WriteLog("CDMA data exception:"+ex.Message);
                    }
                    continue;
                }
                

                byte[] realData = OperateAgreement.RestoreReceData(receData);
                ushort messageId = OperateAgreement.GetMessageIdInMessageHead(realData);
                string phoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);

                if (messageId == ConstParameters.CmdTaxiRegister || messageId == ConstParameters.CmdPhoneUserRegister)
                {

                    #region
                    //    TcpCount  Add 
                    try
                    {
                        PositionService.AsTcpCountAdd(ServerWebIp, phoneNumber);
                        _transferSocket.Send(receData);
                    }
                    catch (Exception ex)
                    {
                        RestTransferSocket();
                        CommonRoutine.HandlingExceptions(ex);
                        LogService.WriteLog("AcceptMainForm.cs-299");
                        return;
                    }
                    #endregion

                }

                if (messageId == ConstParameters.CmdRetweet
                    || messageId == ConstParameters.CmdTaxiTakeAPhotoReply
                    || messageId == ConstParameters.CmdTaxiTakeAVideoReply
                    || messageId == ConstParameters.CmdSendSmsToTaxiReply
                    || messageId == ConstParameters.CmdSendNewsToTaxiReply
                    || messageId == ConstParameters.CmdSendSmsToTaxiReplyRightNow
                    || messageId == ConstParameters.CmdTaxiCutOil
                    || messageId == ConstParameters.CmdTaxiMonitorReply
                    || messageId == ConstParameters.CmdSendByClientPublicId                
                    )
                {
                    #region  Retweet
                    try
                    {
                        IPEndPoint ipEndPoint = null;
                        if (messageId == ConstParameters.CmdRetweet)
                        {
                            string sendtoPhoneNumber = OperateAgreement.GetPhoneNumInTransferMessageHead(realData);
                            ipEndPoint = IpEndPointList[sendtoPhoneNumber] as IPEndPoint;
                        }
                        else
                        {
                            int packetIndex = OperateAgreement.GetPackageIndexInMessageHead(realData);

                            IPEndPoint ipEndPoint2 = IpEndPointList[phoneNumber] as IPEndPoint;
                            if (ipEndPoint2 == null) return;
                            #region Confirm Reply
                            if (messageId == ConstParameters.CmdTaxiTakeAPhotoReply)
                            {
                                byte[] sendData = GetTakePhotoVideoReply(
                                    ConstParameters.CmdTaxiTakeAPhotoReplyReply, packetIndex);
                                //sendSocket.SendTo(sendData, sendData.Length, SocketFlags.None, ipEndPoint2);
                                SendDataToIPAddress(sendData, ipEndPoint2, phoneNumber);
                                #region LogPrint
                                ushort msid = OperateAgreement.GetMessageIdInMessageHead(sendData);
                                LogService.WriteDebugLog("sendLength :" + sendData.Length + "---" + ipEndPoint2 + ",MessidID:" +
                                    msid.ToString("X2").PadLeft(4, '0'), DateTime.Now, "_send");
                                #endregion
                            }
                            if (messageId == ConstParameters.CmdTaxiTakeAVideoReply)
                            {
                                byte[] sendData = GetTakePhotoVideoReply(
                                    ConstParameters.CmdTaxiTakeAVideoReplyReply, packetIndex);

                                // sendSocket.SendTo(sendData, sendData.Length, SocketFlags.None, ipEndPoint2);
                                SendDataToIPAddress(sendData, ipEndPoint2, phoneNumber);
                                #region LogPrint
                                ushort msid = OperateAgreement.GetMessageIdInMessageHead(sendData);
                                LogService.WriteDebugLog("sendLength :" + sendData.Length + "---" + ipEndPoint2 + ",MessidID:" +
                                    msid.ToString("X2").PadLeft(4, '0'), DateTime.Now, "_send");
                                #endregion
                            }
                            #endregion
                        }

                        if (ipEndPoint != null)
                        {
                            SendRetweetData(realData, ipEndPoint);
                        }
                        else
                        {
                            try
                            {
                                //Must be receData
                                _transferSocket.Send(receData);
                            }
                            catch (Exception ex)
                            {
                                RestTransferSocket();
                                CommonRoutine.HandlingExceptions(ex);
                                LogService.WriteLog("AcceptMainForm.cs-380");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        CommonRoutine.HandlingExceptions(ex);
                        LogService.WriteLog("AcceptMainForm.cs-387");
                    }
                    #endregion
                }
                else
                {

                    IPEndPoint ipEndPoint = IpEndPointList[phoneNumber] as IPEndPoint;
                    if (ipEndPoint == null) continue;
                    byte[] sendData = new byte[1];
                    try
                    {
                        OperateCmdData operateCmdData = new OperateCmdData(); ;
                        sendData = operateCmdData.AnalysisMessageId(realData, ipEndPoint.Address);
                    }
                    catch (Exception ex)
                    {

                        if (realData != null)
                        {
                            LogService.WriteLog(realData.Length.ToString());
                        }
                        else
                        {
                            LogService.WriteLog("realData");
                        }
                        if (ipEndPoint.Address != null)
                        {
                            LogService.WriteLog(ipEndPoint.Address.ToString());
                        }
                        else
                        {
                            LogService.WriteLog("ipEndPoint.Address=null");
                        }
                        CommonRoutine.HandlingExceptions(ex);
                        LogService.WriteLog("AcceptMainForm.cs-405");
                        continue;
                    }
                    #region Send Bytes

                    if (sendData != null && sendData.Length >= ConstParameters.MhLenth)
                    {
                        try
                        {

                            // sendSocket.SendTo(sendData, sendData.Length, SocketFlags.None, ipEndPoint);
                            SendDataToIPAddress(sendData, ipEndPoint, phoneNumber);
                            #region LogPrint

                            ushort msid = OperateAgreement.GetMessageIdInMessageHead(sendData);
                            LogService.WriteDebugLog("sendLength :" + sendData.Length + "---" + ipEndPoint + ",MessidID:" +
                                msid.ToString("X2").PadLeft(4, '0'), DateTime.Now, "_send");
                            #endregion
                        }
                        catch (Exception ex)
                        {
                            CommonRoutine.HandlingExceptions(ex);
                            LogService.WriteLog("AcceptMainForm.cs-428");
                            continue;
                        }
                    }
                    #endregion
                }
            }


            #region LogPrint
            LogService.WriteLog(Thread.CurrentThread.Name + "----Snen Thread 退出----");
            #endregion
        }

        public static Socket JudgeIsUnicomNumber(string phoneNumber)
        {
            #region 单线服务器 处理
            //不会出现这种情况。两个都为空的话没程序就没有收发消息的流程。
            // if (_udpClientUniCom == null && _udpClientChinaNet == null) 
            if (_udpClientUniCom == null && _udpClientChinaNet != null)
            {
                _udpClientUniCom = _udpClientChinaNet;
                return _udpClientChinaNet;
            }
            if (_udpClientUniCom != null && _udpClientChinaNet == null)
            {
                _udpClientChinaNet = _udpClientUniCom;
                return _udpClientUniCom;
            }
            #endregion
            //130、131、132、145、155、156、185、186 
            if (phoneNumber.StartsWith("130") || phoneNumber.StartsWith("131") || phoneNumber.StartsWith("132") ||
                phoneNumber.StartsWith("145") || phoneNumber.StartsWith("155") || phoneNumber.StartsWith("156") ||
                phoneNumber.StartsWith("185") || phoneNumber.StartsWith("186"))
            {
                return _udpClientUniCom;
            }
            else
            {
                return _udpClientChinaNet;
            }
        }


        private void IpEndPointClear()
        {
            while (true)
            {
                Thread.Sleep(180 * 1000);
                DateTime now = DateTime.Now;
                ArrayList delKey = new ArrayList();
                lock (_ipEndPointTimeList.SyncRoot)
                {
                    foreach (DictionaryEntry dictionaryEntry in _ipEndPointTimeList)
                    {
                        DateTime updatatime = (DateTime)dictionaryEntry.Value;
                        TimeSpan timeSpan = new TimeSpan(now.Ticks - updatatime.Ticks);
                        if (timeSpan.TotalSeconds > 180)
                        {
                            delKey.Add(dictionaryEntry.Key);
                            LogService.WriteDebugLog(dictionaryEntry.Key + "---" + now.ToString() + "---" + updatatime.ToString() + "退出登录！", DateTime.Now, dictionaryEntry.Key.ToString());
                        }
                    }
                }

                foreach (string phoneNumber in delKey)
                {
                    try
                    {

                        _ipEndPointTimeList.Remove(phoneNumber);
                        IpEndPointList.Remove(phoneNumber);
                        PositionService.AsTcpCountMinus(ServerWebIp, phoneNumber);
                        try
                        {
                            _transferSocket.Send(GetLogoutSocketInTransferServer(phoneNumber));
                        }
                        catch (Exception ex)
                        {
                            RestTransferSocket();
                            CommonRoutine.HandlingExceptions(ex);
                            LogService.WriteLog("AcceptMainForm.cs-508");
                        }

                    }
                    catch (Exception ex)
                    {
                        CommonRoutine.HandlingExceptions(ex);
                        LogService.WriteLog("AcceptMainForm.cs-515");
                    }

                }
                //清除五分钟内未向服务器发送消息的广告机
                ArrayList delKeyStation = new ArrayList();
                lock (StationList.SyncRoot)
                {
                    foreach (AdStationInfo station in StationList.Values)
                    {
                        DateTime updatatime = station.UpdateTime;
                        TimeSpan timeSpan = new TimeSpan(now.Ticks - updatatime.Ticks);
                        if (timeSpan.TotalSeconds > 300)
                        {
                            delKeyStation.Add(station.Machine.Number);
                            LogService.WriteDebugLog(station.Machine.Number
                                + "---" + now.ToString() + "---"
                                + updatatime.ToString()
                                + "断开连接！", DateTime.Now);
                        }
                    }
                }
                foreach (string number in delKeyStation)
                {
                    StationList.Remove(number);
                }


                Invoke(new MethodInvoker(delegate()
                {
                    label_SokcetCount.Text = IpEndPointList.Count.ToString(CultureInfo.InvariantCulture) + "," + DateTime.Now.ToString();
                }));


            }

        }

        private void TransferSocketRece()
        {
            List<byte> receBufferBb = new List<byte>();
            while (true)
            {

                byte[] receBuffer = new byte[100];
                #region rece Data
                try
                {
                    int receDataLength = _transferSocket.Receive(receBuffer);
                    Thread.Sleep(1);
                    if (receDataLength == 0 || receDataLength == -1)
                    {
                        break;
                    }
                    byte[] temp = new byte[receDataLength];
                    Array.Copy(receBuffer, 0, temp, 0, temp.Length);
                    receBufferBb.AddRange(temp);
                }
                catch (Exception ex)
                {
                    CommonRoutine.HandlingExceptions(ex);
                    LogService.WriteLog("AcceptMainForm.cs-552");
                    _transferSocket.Close();
                    break;
                }


                #endregion


                int receBufferBBindex = 0;
                int sendflag = -1;
                int endindex = 0;
                List<byte> receByteList = new List<byte>();

                foreach (byte b in receBufferBb)
                {
                    receBufferBBindex++;
                    if (b == 0x7e) sendflag++;
                    if (sendflag >= 0)
                    {
                        if (sendflag == 0) { receByteList.Add(b); }
                        else if (sendflag == 1)
                        {
                            receByteList.Add(b);
                            byte[] receData = receByteList.ToArray();
                            receByteList.Clear();
                            sendflag = -1;
                            endindex = receBufferBBindex;
                            #region
                            byte[] realData = OperateAgreement.RestoreReceData(receData);
                            if (OperateAgreement.JudgeisCompleteData(realData))
                            {
                                string sendtoPhoneNumber = OperateAgreement.GetPhoneNumInTransferMessageHead(realData);
                                IPEndPoint ipEndPoint = IpEndPointList[sendtoPhoneNumber] as IPEndPoint;
                                if (ipEndPoint != null)
                                {
                                    SendRetweetData(realData, ipEndPoint);
                                    string phoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);
                                    ushort realMessageId = OperateAgreement.GetMessageIdInTransferMessageHead(realData);
                                    ushort messageId = OperateAgreement.GetMessageIdInMessageHead(realData);
                                    #region LogPrint
                                    LogService.WriteDebugLog2("转发成功-------------sendtoPhoneNumber：" + sendtoPhoneNumber + "realMessageId消息Id：0x"
                                        + realMessageId.ToString("X2").PadLeft(4, '0') + "phoneNumber:" + phoneNumber
                                        + "messageId:" + messageId.ToString("X2").PadLeft(4, '0'), DateTime.Now, "Retweet");
                                    #endregion

                                }
                                else
                                {
                                    LogService.WriteDebugLog("找不到" + sendtoPhoneNumber + "Socket, 转发失败++。", DateTime.Now, "Retweet");
                                }
                            }

                            #endregion
                        }
                    }
                }
                if (endindex > 0)
                {
                    receBufferBb.RemoveRange(0, endindex);
                }



            }
            RestTransferSocket();
        }

        private void RestTransferSocket()
        {
            if (_tTransferSocketRece != null) _tTransferSocketRece.Abort();
            Thread.Sleep(500);
            if (_transferSocket != null)
            {
                _transferSocket.Shutdown(SocketShutdown.Both);
                _transferSocket.Close();
                _transferSocket.Dispose();
            }

            IpEndPointList.Clear();
            _ipEndPointTimeList.Clear();
            LogService.WriteDebugLog("_transferSocket 重新建立连接", DateTime.Now);


            _transferSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint address = new IPEndPoint(IPAddress.Parse(textBox_TransferServerip.Text), ConstParameters.TransferListenPort);
            _transferSocket.Connect(address);

            _tTransferSocketRece = new Thread(TransferSocketRece) { IsBackground = true, Name = "_tTransferSocketRece----------------------------------------------" };
            _tTransferSocketRece.Start();
        }

        private void SendRetweetData(byte[] realData, IPEndPoint ipEndPoint)
        {
            ushort realMessageId = OperateAgreement.GetMessageIdInTransferMessageHead(realData);
            byte[] phoneNumberbyts = new byte[6];
            Array.Copy(realData, 5, phoneNumberbyts, 0, 6);
            byte[] serialNumber = new byte[2];
            Array.Copy(realData, 11, serialNumber, 0, 2);
            bool isSubPackage = OperateAgreement.GetIsSubPackageInMessageHead(realData);
            ushort packageCount = (ushort)OperateAgreement.GetPackageCountInMessageHead(realData);
            ushort packageIndex = (ushort)OperateAgreement.GetPackageIndexInMessageHead(realData);

            //----8===2--messageid+6--phonenumber
            int bodyLength = realData.Length - ConstParameters.MhLenth - 8;
            byte[] sendBody = new byte[bodyLength];
            Array.Copy(realData, ConstParameters.MBodySatrtIndex + 8, sendBody, 0, bodyLength);
            byte[] sendHead = OperateAgreement.GetMessageHead(realMessageId, isSubPackage, false,
                                                              bodyLength, phoneNumberbyts,
                                                              serialNumber, packageCount,
                                                              packageIndex);

            byte[] sendData = OperateAgreement.PackageSendData(sendHead, sendBody);

            try
            {
                string sendtoPhoneNumber = OperateAgreement.GetPhoneNumInTransferMessageHead(realData);

                //sendSocket.SendTo(sendData, sendData.Length, SocketFlags.None, ipEndPoint);

                SendDataToIPAddress(sendData, ipEndPoint, sendtoPhoneNumber);
                #region LogPrint
                ushort msid = OperateAgreement.GetMessageIdInMessageHead(sendData);
                LogService.WriteDebugLog("sendLength :" + sendData.Length + "---" + ipEndPoint + ",MessidID:" +
                    msid.ToString("X2").PadLeft(4, '0'), DateTime.Now, "_send");
                #endregion
            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
                LogService.WriteLog("AcceptMainForm.cs-683");
            }

        }

        private void InitControlAfterStopService()
        {
            spState.Text = @" 监听服务未启动 ...";
            button_startListening.Enabled = true;
            button_stopListening.Enabled = false;
            textBox_PosIP.Enabled = true;
            textBox_ChinaNetIp.Enabled = true;
            textBox_UnicomIp.Enabled = true;
            textBox_TransferServerip.Enabled = true;
            textBox_PhoneNumber.Enabled = true;
            textBox_DataBaseHandlerThreadCount.Enabled = true;
            textBox_DataHandlerThreadCount.Enabled = true;

            textBox_datBaseName.Enabled = true;
            textBox_passWord.Enabled = true;
            textBox_serverName.Enabled = true;
            textBox_userName.Enabled = true;

            if (_threadDataHandler != null)
            {
                //终止所有的数据处理线程
                for (int i = 0; i < _dataHandlerThreadCount; i++)
                {
                    if (this._threadDataHandler[i].IsAlive) this._threadDataHandler[i].Abort();
                }
            }

            if (_threadTaxiGpsHistoryInfoHandler != null)
            {
                //终止所有的数据处理线程
                for (int i = 0; i < _dataBaseHandlerThreadCount; i++)
                {
                    if (this._threadTaxiGpsHistoryInfoHandler[i].IsAlive) this._threadTaxiGpsHistoryInfoHandler[i].Abort();
                }
            }



            if (_transferSocket != null && _transferSocket.Connected)
            {

                _transferSocket.Shutdown(SocketShutdown.Both);
                _transferSocket.Close();
            }



            if (_tTransferSocketRece != null) _tTransferSocketRece.Abort();
            //if (_addTaxiGpsHistoryInfoQueue != null) _addTaxiGpsHistoryInfoQueue.Abort();
            if (_ipEndPointClearThread != null) _ipEndPointClearThread.Abort();
            if (_tCdmaTaxiClearThread!=null)  _tCdmaTaxiClearThread.Abort();             
            if (PositionService != null)
            { PositionService.AcceptServerlogout(ServerWebIp); }
            // if (_server != null) { _server.Stop(); }
        }



        private void InitControlAfterStartService()
        {
            spState.Text = @" 监听服务已启动 ...";
            button_startListening.Enabled = false;
            button_stopListening.Enabled = true;
            textBox_PosIP.Enabled = false;
            textBox_ChinaNetIp.Enabled = false;
            textBox_TransferServerip.Enabled = false;
            textBox_UnicomIp.Enabled = false;
            textBox_PhoneNumber.Enabled = false;
            textBox_DataBaseHandlerThreadCount.Enabled = false;
            textBox_DataHandlerThreadCount.Enabled = false;

            textBox_datBaseName.Enabled = false;
            textBox_passWord.Enabled = false;
            textBox_serverName.Enabled = false;
            textBox_userName.Enabled = false;
        }

        /// <summary>
        ///!--2 return 1 means succeed ,0 means false.
        /// </summary>
        /// <returns></returns>
        private bool InitWcfService(string ip)
        {
            try
            {
                NetTcpBinding netbinding = new NetTcpBinding(SecurityMode.None, true)
                                               {
                                                   MaxBufferPoolSize = 2147483647,
                                                   MaxBufferSize = 2147483647,
                                                   MaxReceivedMessageSize = 2147483647,
                                                   SendTimeout = new TimeSpan(1, 10, 30),
                                                   ReceiveTimeout = new TimeSpan(1, 0, 0),
                                                   ReliableSession = { Enabled = true, InactivityTimeout = new TimeSpan(20, 0, 10) },
                                                   ReaderQuotas =
                                                       {
                                                           MaxArrayLength = 2147483647,
                                                           MaxStringContentLength = 2147483647,
                                                           MaxBytesPerRead = 2147483647
                                                       },
                                                   TransferMode = TransferMode.Buffered,
                                               };
                netbinding.MaxConnections = 65536000;
                ChannelFactory<IPositionService> factory = new ChannelFactory<IPositionService>
                                     (netbinding, new EndpointAddress("net.tcp://" + ip + ":" + Common.ConstParameters.WcfPort + "/PositionServices"));
                foreach (System.ServiceModel.Description.OperationDescription op in factory.Endpoint.Contract.Operations)
                {
                    System.ServiceModel.Description.DataContractSerializerOperationBehavior dataContractBehavior =
                                op.Behaviors.Find<System.ServiceModel.Description.DataContractSerializerOperationBehavior>();
                    if (dataContractBehavior != null)
                    {
                        dataContractBehavior.MaxItemsInObjectGraph = 2147483647;
                    }
                }
                PositionService = factory.CreateChannel();
            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
                LogService.WriteLog("AcceptMainForm.cs-805");
                return false;
            }
            return true;

        }


        private byte[] GetTakePhotoVideoReply(ushort messageId, int packetIndex)
        {
            byte[] phonebytes = new byte[6];
            byte[] body = { (byte)packetIndex };
            byte[] head = OperateAgreement.GetMessageHead(messageId, false, false, body.Length, phonebytes, new byte[2], 0, 0);
            byte[] sendData = OperateAgreement.PackageSendData(head, body);
            return sendData;
        }

        private byte[] GetLogoutSocketInTransferServer(string phoneNumeber)
        {
            byte[] phonebytes = CommonRoutine.BcdStringToBytes(phoneNumeber.PadLeft(12, '0'));
            byte[] body = new byte[] { 0 };
            byte[] head = OperateAgreement.GetMessageHead(ConstParameters.CmdLogoutInTransfer, false, false, body.Length, phonebytes, new byte[2], 0, 0);
            byte[] sendData = OperateAgreement.PackageSendData(head, body);
            return sendData;
        }



        private void button_startListening_Click(object sender, EventArgs e)
        {
            if (!CommonRoutine.IsValidIp(textBox_PosIP.Text))
            {
                MessageBox.Show(@"请检查位置服务器IP格式");
                textBox_PosIP.Focus();
                return;
            }
            if (!CommonRoutine.IsValidIp(textBox_ChinaNetIp.Text))
            {
                MessageBox.Show(@"请检查接入服务器IP1格式");
                textBox_ChinaNetIp.Focus();
                return;
            }
            if (!CommonRoutine.IsValidIp(textBox_UnicomIp.Text))
            {
                MessageBox.Show(@"请检查接入服务器IP2格式");
                textBox_UnicomIp.Focus();
                return;
            }

            if (!CommonRoutine.IsValidIp(textBox_TransferServerip.Text))
            {
                MessageBox.Show(@"请检查中转服务器IP格式");
                textBox_TransferServerip.Focus();
                return;
            }

            if (!int.TryParse(textBox_DataBaseHandlerThreadCount.Text, out _dataBaseHandlerThreadCount))
            {
                MessageBox.Show(@"数据库处理线程数：  请输入数字");
                textBox_DataBaseHandlerThreadCount.Focus();
                return;
            }
            if (!int.TryParse(textBox_DataHandlerThreadCount.Text, out _dataHandlerThreadCount))
            {
                MessageBox.Show(@"网络数据处理线程数 ：请输入数字");
                textBox_DataHandlerThreadCount.Focus();
                return;
            }
            StartServecie();

        }

        private void button_stopListening_Click(object sender, EventArgs e)
        {

            try
            {
                IpEndPointList.Clear();
                _ipEndPointTimeList.Clear();
                label_SokcetCount.Text = "0";
                InitControlAfterStopService();

            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
                LogService.WriteLog("AcceptMainForm.cs-891");
            }

        }

        private void HideServer_Click(object sender, EventArgs e)
        {
            WindowState = FormWindowState.Minimized;
            ShowInTaskbar = false;
            Visible = false;
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            button_startListening.Enabled = true;
            button_stopListening.Enabled = false;
            string[] config = OperateConfig.GetAcceptServerConfig();
            if (config != null && config.Length == 9)
            {
                textBox_PosIP.Text = config[0];
                textBox_ChinaNetIp.Text = config[1];
                textBox_UnicomIp.Text = config[2];
                textBox_PhoneNumber.Text = config[3];
                textBox_TransferServerip.Text = config[4];
                textBox_datBaseName.Text = config[5];
                textBox_serverName.Text = config[6];
                textBox_userName.Text = config[7];
                textBox_passWord.Text = config[8];

                //config[5] = myini.ReadString("DBCONFIG", "DataBaseName", "TaxiDispatchSystem");
                //config[6] = myini.ReadString("DBCONFIG", "ServerName", "127.0.0.1");
                //config[7] = myini.ReadString("DBCONFIG", "UserID", "root");
                //config[8] = myini.ReadString("DBCONFIG", "PassWord", "123456");

            }
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("是否确定关闭接入服务器？", "警告：", MessageBoxButtons.OKCancel)
                == DialogResult.Cancel)
            {
                e.Cancel = true;
                return;
            }
            try
            {
                IpEndPointList.Clear();
                label_SokcetCount.Text = "0";

                InitControlAfterStopService();
                if (PositionService != null)
                { PositionService.AcceptServerlogout(ServerWebIp); }

            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
                LogService.WriteLog("AcceptMainForm.cs-943");
            }
            notifyIcon1.Visible = false;
            Environment.Exit(0);
        }

        private void notifyIcon1_Click(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                WindowState = FormWindowState.Normal;
                ShowInTaskbar = true;
                Visible = true;
                Focus();
            }
            else
            {
                WindowState = FormWindowState.Minimized;
                ShowInTaskbar = false;
                Visible = false;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string showtext = IpEndPointList.Count.ToString();

            //lock (_ipEndPointList.SyncRoot)
            //{
            //    foreach (DictionaryEntry dictionaryEntry in _ipEndPointList)
            //    {
            //        showtext = showtext + dictionaryEntry.Key + Environment.NewLine;
            //    }
            //}
            MessageBox.Show(showtext);
        }

        private void button_TestConnection_Click(object sender, EventArgs e)
        {
            string[] config = new[]
            {
                 textBox_datBaseName.Text,
                 textBox_serverName.Text,
                 textBox_userName.Text,
                textBox_passWord.Text
            };
            OperateConfig.SaveAcceptServerDataBaseConfig(config);
            if (CheckDataBasesConnection())
            {
                BLL.SysManage.UpdataConnectstring();
                MessageBox.Show(@"数据库连接成功！");

            }
        }

        /// <summary>
        ///!--4 return 1 means succeed ,return 0 means false
        /// </summary>
        public bool CheckDataBasesConnection()
        {
            if (BLL.SysManage.CheckDb(textBox_datBaseName.Text) == 0)
            {
                MessageBox.Show(@"系统数据库连接失败！请检查配置。");
                return false;
            }
            return true;
        }



        private void button1_Click(object sender, EventArgs e)
        {
            PrivateCarClientVersion = OperateConfig.GetPrivateCarClientVersion();
            TaxiClientVersion = OperateConfig.GetTaxiClientVersion();
            PhoneUserClientVersion = OperateConfig.GetPhoneUserClientVersion();
            SpecialCarClientVersion = OperateConfig.GetSpecialCarClientVersion();
            int.TryParse(OperateConfig.GetPhonePlatformVersion(), out PhonePlatformVersion);

            label_SokcetCount.Text = IpEndPointList.Count.ToString();
            label_DataHandlerThreadCount.Text = _dateQueue.Count.ToString();
            label_DataBaseHandlerThreadCount.Text = DataQueue.Count.ToString();
            //RentCar_phoneNumbers = LogService.GetRentCarList();

            //StringBuilder sb = new StringBuilder();
            //sb.Append("set names  'utf8';insert into ttaxigpshistory");
            //sb.Append("(DriverPhoneNumber,Longitude,Latitude,Updatetime,Taxistate,image) ");
            //sb.Append("values ");
            //for (int i = 1; i <= 56000; i++)
            //{
            //     sb.Append("('");
            //        sb.Append("13100000000");
            //        sb.Append("','");
            //        sb.Append("115.234567");
            //        sb.Append("','");
            //        sb.Append("36.232477");
            //        sb.Append("','");
            //        sb.Append("2013-05-10 11:00:00");
            //        sb.Append("','");
            //        sb.Append("0");
            //        sb.Append("',");
            //        sb.Append("null)");
            //        if (i != 56000)
            //        {
            //            sb.Append(",");
            //        }
            //} 
            //int rows = _operateDataBase.AddListTaxiGpsHistory(sb.ToString());



            //for (int i = 0; i < 10000; i++)
            //{
            //    TaxiGpsHistoryInfo taxiGpsHistoryInfo = new TaxiGpsHistoryInfo();
            //    taxiGpsHistoryInfo.AlarmL = 0;
            //    taxiGpsHistoryInfo.DriverPhoneNumber = "1000000000" + i.ToString();
            //    taxiGpsHistoryInfo.Latitude = 29.674512;
            //    taxiGpsHistoryInfo.Longitude = 115.982283;
            //    taxiGpsHistoryInfo.Taxistate = 0;
            //    taxiGpsHistoryInfo.Time = DateTime.Now;
            //    DataQueue.Enqueue(taxiGpsHistoryInfo);
            //}



            //TaxiGpsHistoryInfo taxiGpsHistoryInfo=new TaxiGpsHistoryInfo();
            //taxiGpsHistoryInfo.AlarmL = 0;
            //taxiGpsHistoryInfo.DriverPhoneNumber = "18602789588";
            //taxiGpsHistoryInfo.Latitude = 29.674512;
            //taxiGpsHistoryInfo.Longitude = 115.982283;
            //taxiGpsHistoryInfo.Taxistate = 0;
            //taxiGpsHistoryInfo.Time = DateTime.Now;
            //PositionService.AddTaxiGpsHistoryInfo(taxiGpsHistoryInfo);


            return;


            WebClient client = new WebClient();
            string url = "http://www.ip138.com/ips138.asp?ip=111.174.91.101";
            string URL_Content = System.Text.Encoding.GetEncoding("GBK").GetString(client.DownloadData(url));
            Regex Reg = new Regex("<td align=\"center\"><ul class=\"ul1\"><li>(.*?)</li><li>(.*?)</li></ul></td>");
            Match Match = Reg.Match(URL_Content);
            string ipLocal = string.Empty;
            if (Match.Success)
            {
                ipLocal = Match.Groups[1].Value + " " + Match.Groups[2].Value;
                IniFiles myini = new IniFiles(System.Environment.CurrentDirectory + "\\system.ini");
                NameValueCollection nameValue = new NameValueCollection();
                myini.ReadSectionValues("IPCONFIG", nameValue);
                foreach (string key in nameValue.AllKeys)
                {
                    string[] locale = key.Split('|');
                    foreach (string s in locale)
                    {
                        if (ipLocal.Contains(s))
                        {
                            var strings = nameValue.GetValues(key);
                            //   if (strings != null) return strings[0];
                        }
                    }
                }
            }


            //IPAddress sdsd = IPAddress.Parse("127.0.0.1");
            //WebClient client = new WebClient();
            //string url = "http://www.ip138.com/ips138.asp?ip=111.174.91.101";
            //string sdsds = "";

            //int ii = 0;
            //int y = 0;
            //for (int i = 0; i < 10000; i++)
            //{
            //    string URL_Content = System.Text.Encoding.GetEncoding("GBK").GetString(client.DownloadData(url));
            //    Regex Reg = new Regex("<td align=\"center\"><ul class=\"ul1\"><li>(.*?)</li><li>(.*?)</li></ul></td>");
            //    Match Match = Reg.Match(URL_Content);
            //    if (Match != null && Match.Success)
            //    {
            //        sdsds += (Match.Groups[1].Value + " " + Match.Groups[2].Value) + Environment.NewLine;
            //        ii++;
            //    }
            //    else
            //    {
            //        y++;
            //    }
            //}






            //int sdsd = PositionService.TestWCF();
            string phoneNumber = "11111111111";
            //int count = 0;
            //count = AcceptMainForm.PositionService.GetRecordCountOfUserInThisMonth(phoneNumber, 1);
            //count++;

            //_server.SendData(new byte[10], ipep);
            //button1.Text = _dateQueue.Count.ToString();
            //   _tTransferSocketRece.Abort();
            //   _transferSocket.Close();
            //_transferSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //IPEndPoint address = new IPEndPoint(IPAddress.Parse(textBox_TransferServerip.Text), ConstParameters.TransferListenPort);

            //_transferSocket.Connect(address);

            //_transferSocket.Close();

            //_transferSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //_transferSocket.Connect(address);

            //_ipEndPointTimeList["11"] = DateTime.Now;
            //// Thread.Sleep(1000);
            //foreach (DictionaryEntry dictionaryEntry in _ipEndPointTimeList)
            //{
            //    DateTime updatatime = (DateTime)dictionaryEntry.Value;
            //    TimeSpan timeSpan = new TimeSpan(updatatime.Ticks - DateTime.Now.Ticks);
            //    int sadsd = timeSpan.Seconds;
            //    DateTime date = (DateTime)_ipEndPointTimeList["11"];

            //}
            //  byte[] receData = _dataQueue.First.Value;
            //byte[] dsds = CommonRoutine.BcdStringToBytes("99");
            //for (int i = 0; i < 2000; i++)
            //{
            //    Thread.Sleep(100);
            //    Thread d = new Thread(sd);
            //    d.Start(i);
            //}


            //IPAddress[] sdsd= Dns.GetHostAddresses("otech8.gicp.net");
            //ArrayList altemp = _socketList[1] as ArrayList;
            //  List<byte> byteList = new List<byte>();
            //MessageId
            //  byteList.AddRange(BitConverter.GetBytes(messageId).Reverse());
            //  _socketList.Remove(1);
            //ArrayList al=new ArrayList();

            //al.Remove(0);

            //int sdsd = PositionService.SendSms("18907143960", "HelloWrold");
            //string aa = DateTime.Now.ToString("yyyy-MM-dd");
            //DateTime d = DateTime.Now.ToShortDateString();
            //string bb = DateTime.Today.ToShortDateString();

            //DateTime d = DateTime.Parse(bb);

            //byte[] sss = Encoding.GetEncoding("GBK").GetBytes("Sherry");
            //string sds = Common.CommonRoutine.ByteToHexStr(sss);
            //Model.TaxiGpsHistoryInfo taxiGps = new TaxiGpsHistoryInfo();
            //taxiGps.DriverPhoneNumber = "18602789588";
            //taxiGps.Latitude = 20;
            //taxiGps.Longitude = 30;
            //taxiGps.Taxistate = 0;
            //taxiGps.Time = DateTime.Now;
            //List<byte> list=new List<byte>();
            //for (int i = 0; i < 5000; i++)
            //{
            //    Random r = new Random();
            //    int dd = r.Next(0, 253);
            //    list.Add((byte)dd);
            //}
            //taxiGps.Image = list.ToArray();







            // PositionService.AddTaxiGpsHistoryInfo(taxiGps);
            //ArrayList al = null;
            //while (al == null)
            //{
            //    al = PositionService.ReadSms();
            //}
            //int sdsd = PositionService.SendSms("18602789588", "HelloWrold");

            //bool sds = true;
            //while (sds)
            //{
            //    sds = !PositionService.SmsQuery(sdsd);
            //}
            //System.Diagnostics.Stopwatch myWatch = new System.Diagnostics.Stopwatch();
            //myWatch.Start();
            //myWatch.Stop();
            //Console.WriteLine("耗时：" + myWatch.ElapsedMilliseconds + "ms");
            //Serverip = textBox_accpetServerIp.Text;
            //Thread a=new Thread(test);
            //a.Start();
            //Thread b = new Thread(test2);
            //b.Start();
            //hashtable["1"] = "aaa";
            //hashtable.Add("1","ccc");
            //Console.WriteLine(hashtable["1"].ToString());
            //string S = "20111220122916";
            //DateTime dt = DateTime.ParseExact(S, "yyyyMMddHHmmss", null);
            //DateTime sds = DateTime.ParseExact("20111220122500", "yyyyMMddHHmmss ", null, DateTimeStyles.None);

            //DateTime dtNow = DateTime.Now;
            //DateTime sssss = DateTime.Parse("2011-12-19 10:45:30");
            //TimeSpan timeSpan = new TimeSpan(dtNow.Ticks - sssss.Ticks);
            //double sssssssadas = timeSpan.TotalMilliseconds;
            //IPAddress ip = IPAddress.Parse("192.168.0.1");
            //byte[] ssss = ip.GetAddressBytes();
            //byte ssasdcx = 0xff;

            //byte[] Latitude = Common.CommonRoutine.BcdStringToBytes((20.123456 * Math.Pow(10, 6)).ToString().PadLeft(10, '0'));

            //ushort aaaaa = 0x8001;
            //byte[] ss = BitConverter.GetBytes(aaaaa); //01 80
            //ushort sasdas = BitConverter.ToUInt16(ss, 0);
            //short aa = 0x7FFF;
            //byte[] aas = BitConverter.GetBytes(aa);
            //short sssdsa = Convert.ToInt16(aas);
            ////    byte[] sssssssssss = OperateCmdData.BcdStringToBytes("18602789588");
            ////string sssss = Common.CommonRoutine.IntToBinaryString(ss).PadLeft(10, '0');
            //byte[] sss = Encoding.GetEncoding("GBK").GetBytes("鄂JC1588");
            ////string ss = Common.CommonRoutine.IntToBinaryString(255);
        }

        private void button_SendAD_Click(object sender, EventArgs e)
        {
            string adContent = OperateConfig.GetAdContent();
            byte[] mbodydata = Encoding.GetEncoding("GBK").GetBytes(adContent);
            byte[] mHead = OperateAgreement.GetMessageHead(ConstParameters.CmdSendADToStation, false, false, mbodydata.Length, new byte[6],
                              new byte[2], 0, 0);
            byte[] tempData1 = OperateAgreement.PackageSendData(mHead, mbodydata);

            lock (IpEndPointList.SyncRoot)
            {
                foreach (var obj in IpEndPointList.Values)
                {
                    IPEndPoint ipEndPoint = obj as IPEndPoint;
                    if (ipEndPoint != null && _udpClientChinaNet != null && _udpClientUniCom != null)
                    {

                        _udpClientChinaNet.SendTo(tempData1, tempData1.Length, SocketFlags.None, ipEndPoint);
                        _udpClientUniCom.SendTo(tempData1, tempData1.Length, SocketFlags.None, ipEndPoint);
                    }
                }
            }
        }


        private void CdmaTaxiUpdate()
        {
            while (true)
            {
                Thread.Sleep(180 * 1000);
                DateTime now = DateTime.Now;
                ArrayList delKey = new ArrayList();
                ArrayList modifyKey = new ArrayList();
                DataSet ds = _operateDataBase.CdmaTaxiGetList();
                if (ds==null || ds.Tables.Count==0)
                {
                    continue;
                }
                lock (CdmaTaxiList.SyncRoot)
                {
                    foreach (DictionaryEntry dictionaryEntry in CdmaTaxiList)
                    {
                        TaxiCdmaInfo model = (TaxiCdmaInfo)dictionaryEntry.Value;
                        TimeSpan timeSpan = new TimeSpan(now.Ticks - model.UpdateTime.Ticks);
                        if (timeSpan.TotalSeconds > 120)
                        {
                            delKey.Add(dictionaryEntry.Key);
                            LogService.WriteDebugLog(dictionaryEntry.Key + "---" + now.ToString() + "---" + model.UpdateTime  + "退出登录！", DateTime.Now, dictionaryEntry.Key.ToString());
                        }

                        DataRow[] rows =ds.Tables[0].Select("DeviceNumber='" + model.DeviceNumber+"'");
                        if (rows.Length==0)
                        {
                            delKey.Add(model.DeviceNumber);
                        }
                        else
                        {
                            if (model.TaxiNo!=rows[0]["TaxiNo"].ToString() ||
                                model.DriverDay != rows[0]["DriverDay"].ToString() ||
                                model.DriverNight != rows[0]["DriverNight"].ToString() ||
                                model.PhoneNumberDay != rows[0]["PhoneNumberDay"].ToString() ||
                                model.PhoneNumberNight != rows[0]["PhoneNumberNight"].ToString())
                            {
                                modifyKey.Add(model.DeviceNumber);
                            }
                        }
                    }
                }

                foreach (string deviceNumber in delKey)
                {
                    try
                    {
                        TaxiCdmaInfo model = (TaxiCdmaInfo)CdmaTaxiList[deviceNumber];
                        if (model!=null)
                        {
                            PositionService.RemoveCdmaTaxi(model.PhoneNumberDay);
                            PositionService.RemoveCdmaTaxi(model.PhoneNumberNight);
                            CdmaTaxiList.Remove(deviceNumber);                             
                        }                        
                    }
                    catch (Exception ex)
                    {
                        CommonRoutine.HandlingExceptions(ex);
                        LogService.WriteLog("CdmaTaxiUpdate.cs-1548");
                    }

                }
                foreach (string devicNumber in modifyKey)
                {
                    TaxiCdmaInfo model = (TaxiCdmaInfo)CdmaTaxiList[devicNumber];
                    DataRow[] rows = ds.Tables[0].Select("DeviceNumber='" + devicNumber + "'");
                    if (model!=null && rows.Length > 0)
                    {

                        PositionService.RemoveCdmaTaxi(model.PhoneNumberDay);
                        PositionService.RemoveCdmaTaxi(model.PhoneNumberNight);

                        model.TaxiNo = rows[0]["TaxiNo"].ToString();
                        model.DriverDay = rows[0]["DriverDay"].ToString();
                        model.DriverNight = rows[0]["DriverNight"].ToString();
                        model.PhoneNumberDay = rows[0]["PhoneNumberDay"].ToString();
                        model.PhoneNumberNight = rows[0]["PhoneNumberNight"].ToString(); 
                    }
                }
                
            }

        }

         

        #region For Test
        //private void test()
        //{
        //    while (true)
        //    {
        //        MainForm.PositionService.AsTcpCountAdd(Serverip);
        //        Thread.Sleep(500);
        //    }
        //}
        //private void test2()
        //{
        //    while (true)
        //    {
        //        MainForm.PositionService.AsTcpCountMinus(Serverip);
        //        Thread.Sleep(800);
        //    }
        //}
        //private void button1_Click(object sender, EventArgs e)
        //{
        //    Thread t = new Thread(ss);
        //    t.Start();
        //}

        //public void ss()
        //{
        //    double lon = 20.00;
        //    double lat = 120.00;
        //    System.Diagnostics.Stopwatch myWatch = new System.Diagnostics.Stopwatch();
        //    myWatch.Start();
        //    List<Model.TaxiInfo> sInts = _iPositionService.GetNearbyGps(lon, lat, 3000);
        //    myWatch.Stop();
        //    Console.WriteLine("耗时：" + myWatch.ElapsedMilliseconds + "ms");
        //}
        #endregion
    }



    //public class ClientObject
    //{
    //    public IPEndPoint ipEndPoint;
    //    public DateTime updataTime;
    //}

    //public class StateObject
    //{
    //    public TcpClient WorkSocket = null;       // Client  socket.
    //    public const int BufferSize = 1050;       // Size of receive buffer.
    //    public byte[] Buffer = new byte[BufferSize]; // Receive buffer.

    //    public StateObject()
    //    {
    //        // 
    //        // TODO: 在此处添加构造函数逻辑
    //        //
    //    }
    //}
}
